package cn.gok.lambda;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

class Book{
    private float price ;
    private String name;
    private int pageCount;

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public Book(float price, String name, int pageCount) {
        this.price = price;
        this.name = name;
        this.pageCount = pageCount;
    }

    @Override
    public String toString() {
        return "Book{" +
                "price=" + price +
                ", name='" + name + '\'' +
                ", pageCount=" + pageCount +
                '}';
    }
}
public class Stream操作 {
    public static void main(String[] args) {
        //流构造();
        //流的中间操作1();
        流的中间操作2();
    }

    private static void 流的中间操作2() {
        List<Book> list = Arrays.asList(new Book(100f, "西游记", 20),
                new Book(200f, "东游记", 50),
                new Book(300f, "西厢记", 60));
        Stream<Book> s = list.stream();
        s.filter((book -> {return book.getPrice()<250&&book.getPageCount()>20;})).forEach(System.out::println);
    }

    private static void 流的中间操作1() {
        List<Integer> list = Arrays.asList(100, 21, 10, 8, 21, 16);
        Stream<Integer> s = list.stream();
        s.filter(x->x<100).sorted(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if (o1>o2){
                    return -1;
                }
                return 1;
            }
            //2 排序-->从小到大
            //3 去重复
        }).distinct().forEach(System.out::println);
    }

    private static void 流构造() {
        //从常数构造流
        Stream<String> s1 = Stream.of("a", "b", "c");
        //对流中的每一个元素，依次执行consumer函数
        s1.forEach(System.out::println);
        System.out.println("-----");
        //从集合构造流
        List<Integer> list = Arrays.asList(100, 21, 10, 16);
        Stream<Integer> s2 = list.stream();
        s2.forEach(System.out::println);
        System.out.println("-----");
        //3 利用算法构造流。举例，生成随机小数的10位元素的流
        Stream<Double> s3 = Stream.generate(() -> Math.random()).limit(10);
        s3.forEach(System.out::println);
    }
}
